package com.android.webcamsViewer;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.ListAdapter;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;

public class WebcamsGrid extends Activity {
	// Static attributes
	/** Actions **/
	private static final int WEBCAM_ADDER = 0;
	private static final int WEBCAM_VIEW = 1;
	private static final int WEBCAM_REMOVE = 2;
	private static final int WEBCAMS_REFRESH = 3;
	private static final int APP_CLOSE = 4;
	/** Dialogs **/
	private static final int PROGRESS_DIALOG = 1;
	private static final int REMOVE_DIALOG = 2;

	private static final String TAG = "WebcamsGrid";

	// Attributes
	private GridView gridview = null;
	private ImageAdapter adp = null;
	private ProgressDialog progressDialog;
	private AlertDialog alertDialog;
	private int position = 0;
	private WebcamList list = null;

	/** Called when the activity is first created. */
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		// Check length list images
		list = new WebcamList(this);
		launchActivity(WEBCAMS_REFRESH);
	}

	/**
	 * Handler event onCreateOptionsMenu
	 */
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.menu_main, menu);
		return true;
	}

	/**
	 * Handler event onOptionsItemSelect
	 */
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle item selection
		switch (item.getItemId()) {

		// Create new activity with add form
		case R.id.add:
			launchActivity(WEBCAM_ADDER);
			return true;

			// Refresh Images Grid
		case R.id.refresh:
			launchActivity(WEBCAMS_REFRESH);
			return true;

			// Stop app
		case R.id.quit:
			launchActivity(APP_CLOSE);
			return true;
		default:
			return super.onOptionsItemSelected(item);
		}
	}

	/**
	 * Handler when activity finish
	 */
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		// If data is null, UI should not be updated
		if(data != null) {
			switch (requestCode) {
			case WEBCAM_ADDER:
				// Refresh images grid when an image was added
				launchActivity(WEBCAMS_REFRESH);
				return;
			case WEBCAM_VIEW:
				launchActivity(WEBCAMS_REFRESH);
				return;
			default:
				return;
			}
		}
	}

	/**
	 * Manager create dialog
	 */
	protected Dialog onCreateDialog(int id) {
		switch (id) {
		case PROGRESS_DIALOG:
			progressDialog = new ProgressDialog(WebcamsGrid.this);
			progressDialog.setMessage(getText(R.string.loading));
			return progressDialog;
		case REMOVE_DIALOG:
			AlertDialog.Builder builder = new AlertDialog.Builder(this);
			builder.setMessage(getText(R.string.msgRemove));
			builder.setCancelable(false);
			builder.setPositiveButton(getText(R.string.yes),
					new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int id) {
							dialog.dismiss();
							launchActivity(WEBCAM_REMOVE);
						}
					});
			builder.setNegativeButton(getText(R.string.no),
					new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int id) {
							dialog.cancel();
						}
					});
			alertDialog = builder.create();
			return alertDialog;
		default:
			return null;
		}
	}

	/**
	 * Launch a new activity
	 * 
	 * @param activity
	 *            Id Activity
	 */
	protected void launchActivity(int activity) {
		Intent i = null;
		switch (activity) {
		case WEBCAM_ADDER:
			i = new Intent(this, WebcamAdder.class);
			i.putExtra("position", -1);
			startActivityForResult(i, WEBCAM_ADDER);
			return;
		case WEBCAM_VIEW:
			i = new Intent(this, WebcamView.class);
			i.putExtra("position", position);
			startActivityForResult(i, WEBCAM_VIEW);
			return;
		case WEBCAM_REMOVE:
			// Update position
			WebcamList list = new WebcamList(WebcamsGrid.this);
			list.removeWebcam(position);
			launchActivity(WEBCAMS_REFRESH);
			return;
		case WEBCAMS_REFRESH:
			onRefresh();
			return;
		case APP_CLOSE:
			super.finish();
			this.finish();
			return;
		default:
			return;
		}

	}

	/**
	 * Refresh Webcams Grid
	 */
	protected void onRefresh() {
		if (list.getLength() > 0) {
			// Reset list content
			list.reset();

			setContentView(R.layout.main);

			// Free memory
			if (adp != null) {
				try {
					adp.finalize();
				} catch (Throwable e) {
					Log.d(TAG, "Error to free memory", e);
				}
			}

			// Create a new image adapter
			adp = new ImageAdapter(this.getApplicationContext());

			// Download images files asynchronously
			ResetGridViewTask task = new ResetGridViewTask();
			task.execute();

			// Set grid view
			gridview = (GridView) findViewById(R.id.gridview);
			gridview.setAdapter(adp);

			// New Activity to show Maximized Image
			gridview.setOnItemClickListener(new OnItemClickListener() {
				public void onItemClick(AdapterView<?> parent, View v, int pos,
						long id) {
					position = pos;
					launchActivity(WEBCAM_VIEW);
				}
			});

			// Dialog to remove image
			gridview.setOnItemLongClickListener(new OnItemLongClickListener() {
				public boolean onItemLongClick(AdapterView<?> parent, View v,
						int pos, long id) {
					position = pos;
					showDialog(REMOVE_DIALOG);
					return true;
				}
			});
		} else {
			setContentView(R.layout.noimages);
		}
	}

	/**
	 * SetProgress ProgressDialog Handler
	 */
	public void setProgress(Bitmap bm) {
		adp.addImage(bm);
		gridview.invalidateViews();
	}

	/**
	 * Asynchronous task to starts a grid view
	 */
	public class ResetGridViewTask extends AsyncTask<String, Bitmap, Bitmap[]> {

		/**
		 * Handler onPreExecute event
		 */
		protected void onPreExecute() {
			// Create an new progress dialog
			showDialog(PROGRESS_DIALOG);
		}

		/**
		 * Method executed in background thread
		 */
		protected Bitmap[] doInBackground(String... params) {
			Bitmap[] images = new Bitmap[list.getLength()];
			ImageLoader imgLoader = new ImageLoader();

			for (int i = 0; i < list.getLength(); i++) {
				Bitmap bm = imgLoader.loader(list.getWebcam(i).getUrl());
				images[i] = bm;
				publishProgress(bm);
			}
			return images;
		}

		/**
		 * Handler on Progress Update
		 */
		protected void onProgressUpdate(Bitmap... values) {
			super.onProgressUpdate(values);
			setProgress(values[0]);
		}

		/**
		 * Handler onPostExecuteEvent
		 */
		protected void onPostExecute(Bitmap[] result) {
			super.onPostExecute(result);
			// Hide Progress Dialog
			dismissDialog(PROGRESS_DIALOG);
		}
	}
}